<?php

use Illuminate\Database\Capsule\Manager as DB;

#[代理商管理]
class AgentController extends AcommonController
{

    public function init()
    {
        $this->model      = (new memberModel)->where('level', '>', 0);
        $this->table      = 'member';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[代理商列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()) {
            $startOn = $this->get('start_on');
            if (!empty($startOn)) {
                array_push($this->condition, ['created_at', '>=', $startOn]);
            }
            $endOn = $this->get('end_on');
            if (!empty($endOn)) {
                array_push($this->condition, ['created_at', '<=', $endOn]);
            }
            $level = $this->get('level');
            if ($level) {
                array_push($this->condition, ['level', '=', $level]);
            }
            $keywordsType = $this->get('keywordsType');
            $keywords     = $this->get('keywords');
            if ($keywords) {
                array_push($this->search, [$keywordsType, '=', $keywords]);
            }
            $returnData = parent::indexAction(true);

            foreach ($returnData['rows'] as $k => &$v) {
                $cfmember_id = DB::table('member_children')->where('member_id', $v['id'])->where('children_deleted', 0)->where('level', 1)->orderBy('id', 'ASC')->value('children_id');
                if($cfmember_id>0) {
                    $cfmember                = DB::table('member')->where('id', $cfmember_id)->first();
                    $v['cfteam_consume']     = $cfmember->team_consume;
                    $v['cfteam_consume_num'] = $cfmember->team_consume_num;
                }else{
                    $v['cfteam_consume']     = 0.00;
                    $v['cfteam_consume_num'] = 0;
                }
                $v['child_user_count'] = DB::table('member_children')->where('member_id', $v['id'])->where('children_deleted', 0)->count();
                $child_v1 = DB::table('member_children')->where('level', 1)->where('member_id', $v['id'])->where('children_deleted', 0)->pluck('children_id');
                $v['child_user_count_v1'] = count($child_v1);
            }
            json($returnData);
        } else {
            $this->_view->assign('agentLevel', agentlevelModel::select('level', 'name')->get()->toJson());
            parent::indexAction();
        }
    }

    #[代理设置]
    public function configAction()
    {
        if ($this->isPost()) {
            foreach ($this->postData as $k => $v) {
                if ($k == 'become_agent') {
                    if ($v['type'] == 'goods') {
                        $v['value'] = implode(',', $v['value']);
                    }
                    $v = json_encode($v);
                }
                agentconfigModel::where('name', $k)->update(['value' => $v]);
            }
            ret(0, '代理设置更新成功');
        } else {
            $this->_view->assign('dataset', agentconfigModel::all()->pluck('value', 'name')->toJson());
            $this->_view->display('agent/config.html');
        }
    }

    #[代理资格商品]
    public function qualifyGoodsAction()
    {
        $goodsIds = $this->get('goods_ids');
        if (is_string($goodsIds)) {
            $goodsIds = explode(',', $goodsIds);
        }
        $goods      = goodsModel::whereIn('id', $goodsIds)->select('id', 'image', 'title', 'price')->get();
        $goodsStock = goodsskupriceModel::select(DB::raw('sum(stock) as allstock'), 'goods_id')->groupBy('goods_id')->pluck('allstock', 'goods_id');
        foreach ($goods as $k => &$v) {
            $v->stock = $goodsStock[$v->id];
        }
        ret(0, '代理商品', $goods);
    }

    #[代理资格商品刷新]
    public function goodsflushAction()
    {
        $cfgVal          = agentconfigModel::where('name', 'become_agent')->value('value');
        $cfgVal          = json_decode($cfgVal, true);
        $cfgVal['value'] = implode(',', $this->get('goods'));
        agentconfigModel::where('name', 'become_agent')->update(['value' => json_encode($cfgVal)]);
        ret(0, '代理商品更新成功');
    }

    #[选择代理资格商品]
    public function goodsaddAction($returnData = FALSE)
    {
        if ($this->isPost()) {
            $query    = new goodsModel();
            $keywords = $this->get('keywords');
            if (!empty($keywords)) {
                $query = $query->where('title', 'like', "%{$keywords}%");
            }
            $total = $query->count();
            $sort  = $this->get('sort', 'sortorder');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page  = $this->get('page');
            if (!empty($page)) {
                $limit  = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query  = $query->offset($offset)->limit($limit);
            }
            $rows       = $query->get();
            $goodsStock = goodsskupriceModel::select(DB::raw('sum(stock) as allstock'), 'goods_id')->groupBy('goods_id')->pluck('allstock', 'goods_id');
            foreach ($rows as $row) {
                $row->stock = $goodsStock[$row->id];
            }
            json(['total' => $total, 'rows' => $rows]);
        } else {
            $cfgVal   = agentconfigModel::where('name', 'become_agent')->value('value');
            $cfgVal   = json_decode($cfgVal, true);
            $cfgGoods = explode(',', $cfgVal['value']);
            $this->_view->assign('cfgGoods', json_encode($cfgGoods));
            $this->_view->display(strtolower($this->controller) . '/goodsadd.html');
        }
    }

    #[代理商品]
    public function goodsAction()
    {
        if ($this->isPost()) {
            $query    = new goodsModel();
            $query    = $query->leftJoin('agent_goods', 'goods.id', '=', 'agent_goods.goods_id');
            $keywords = $this->get('keywords');
            if (!empty($keywords)) {
                array_push($this->search, ['id', '=', $keywords]);
                array_push($this->search, ['title', 'like', "%{$keywords}%", 'or']);
            }
            if (!empty($this->search)) {
                $query = $query->where(function ($query) {
                    foreach ($this->search as $v) {
                        if (isset($v[3]) && strtolower($v[3]) == 'or') {
                            $query = $query->orWhere([$v]);
                        } else {
                            $query = $query->where([$v]);
                        }
                    }
                });
            }
            $total = $query->count();
            $sort  = $this->get('sort', 'sortorder');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page  = $this->get('page');

            if (!empty($page)) {
                $limit  = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query  = $query->offset($offset)->limit($limit);
            }
            $rows = $query->get();

            json(['total' => $total, 'rows' => $rows]);
        } else {
            $this->_view->display('agent/goods.html');
        }
    }

    #[设置分红]
    public function bonusAction()
    {
        if ($this->isPost()) {
            $rows = $this->postData;
            $event = 'edit';
            $current_agentgoods = agentgoodsModel::query()->where('goods_id', $rows['goods_id'])->first();
            if($current_agentgoods){
                if($current_agentgoods->status == 1 && $rows['status'] == 0){
                    $event = 'del';
                }
                if($current_agentgoods->status == 0 && $rows['status'] == 1){
                    $event = 'add';
                }
            }else{
                $event = 'add';
            }
            agentgoodsModel::updateOrInsert(
                ['goods_id' => $rows['goods_id']],
                $rows
            );
            \app\modules\Admin\service\Agentgoodslog::addLog([
                'goods_id' => $rows['goods_id'],
                'event' => $event,
                'oper_type' => 'admin',
                'oper_id' => $this->auth->user_id
            ]);
            ret(0, '代理商品分红设置成功');
        } else {
            $id = $this->get('id');
            $this->_view->assign('goodsDetail', goodsModel::find($id)->toJson());
            $levelList       = agentlevelModel::get();
            $gudongLevelList = gudonglevelModel::with('levelInfo')->get();
            $tuikeLevelList  = tuikelevelModel::get();
            $qudaiLevelList  = qudailevelModel::query()->orderBy('level', 'DESC')->get();
            $tuiguangLevelList  = twostagelevelModel::get();
            $guquanDefault = configModel::query()->where('type', 19)->whereIn('key', ['jindou_text', 'jindou_self_ratio', 'jindou_tuijian_ratio'])->pluck('value', 'key');
            if($guquanDefault){
                $guquanDefaultList = $guquanDefault->toArray();
                unset($guquanDefault);
            }else{
                $guquanDefaultList = [
                    'jindou_text' => '金豆',
                    'jindou_self_ratio' => '0',
                    'jindou_tuijian_ratio' => '0'
                ];
            }
            $quanyiDefault = configModel::query()->where('type', 19)->whereIn('key', ['quanyi_text', 'quanyi_ratio'])->pluck('value', 'key');
            if($quanyiDefault){
                $quanyiDefaultList = $quanyiDefault->toArray();
                unset($quanyiDefault);
            }else{
                $quanyiDefaultList = [
                    'quanyi_text'  => '权益分红',
                    'quanyi_ratio' => '0',
                ];
            }
            $dianpuDefault = configModel::query()->where('type', 19)->whereIn('key', ['dianpufenhong_text', 'dianpufenhong_self_ratio'])->pluck('value', 'key');
            if($dianpuDefault){
                $dianpuDefaultList = $dianpuDefault->toArray();
                unset($dianpuDefault);
            }else{
                $dianpuDefaultList = [
                    'dianpufenhong_text'  => '店铺分红',
                    'dianpufenhong_ratio' => '0',
                ];
            }
            if (agentgoodsModel::where('goods_id', $id)->exists()) {
                $agentGoods = agentgoodsModel::find($id);
                $this->_view->assign('params', $agentGoods->toJson());
                if (!$agentGoods->jc_rules || !$agentGoods->pj_level1_rules || !$agentGoods->pj_level2_rules || !$agentGoods->gd_rules) {
                    $jc_rules = [];
                    foreach ($levelList as $oneLevel) {
                        array_push($jc_rules, [
                            'level' => $oneLevel->level,
                            'money' => '',
                            'ratio' => '',
                        ]);
                    }
                }
                $this->_view->assign('commission_rules', $agentGoods->jc_rules ?: json_encode($jc_rules));
                $this->_view->assign('gd_rules', $agentGoods->gd_rules ?: json_encode($jc_rules));
                $this->_view->assign('pj_level1_rules', $agentGoods->pj_level1_rules ?: json_encode($jc_rules));
                $this->_view->assign('pj_level2_rules', $agentGoods->pj_level2_rules ?: json_encode($jc_rules));
                $tk_rules = [];
                foreach ($tuikeLevelList as $oneLevel) {
                    array_push($tk_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('tk_zhitui_rules', $agentGoods->tk_zhitui_rules ?: json_encode($tk_rules));
                $this->_view->assign('tk_jiantui_rules', $agentGoods->tk_jiantui_rules ?: json_encode($tk_rules));
                if (!$agentGoods->qd_rules) {
                    $qd_rules = [];
                    foreach ($qudaiLevelList as $oneLevel) {
                        array_push($qd_rules, [
                            'level' => $oneLevel->level,
                            'money' => '',
                            'ratio' => '',
                        ]);
                    }
                }
                $this->_view->assign('qd_rules', $agentGoods->qd_rules ?: json_encode($qd_rules));
                $tg_rules = [];
                foreach ($tuiguangLevelList as $oneLevel) {
                    array_push($tg_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('tg_level1_rules', $agentGoods->tg_level1_rules ?: json_encode($tg_rules));
                $this->_view->assign('tg_level2_rules', $agentGoods->tg_level2_rules ?: json_encode($tg_rules));
                $gq_rules = [
                    'money' => '',
                    'ratio' => '',
                ];
                $this->_view->assign('gq_zigou_rules', $agentGoods->gq_zigou_rules ?: json_encode($gq_rules));
                $this->_view->assign('gq_tuijian_rules', $agentGoods->gq_tuijian_rules ?: json_encode($gq_rules));
                $qy_rules = [
                    'money' => '',
                    'ratio' => '',
                ];
                $this->_view->assign('qy_rules', $agentGoods->qy_rules ?: json_encode($qy_rules));
                $dianpu_rules = [
                    'money' => '',
                    'ratio' => '',
                ];
                $this->_view->assign('dianpu_rules', $agentGoods->dianpu_rules ?: json_encode($dianpu_rules));
            } else {
                $agent_goods             = $this->getTableColumn('agent_goods');
                $agent_goods['goods_id'] = $id;
                $this->_view->assign('params', json_encode($agent_goods));
                $jc_rules = [];
                foreach ($levelList as $oneLevel) {
                    array_push($jc_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('commission_rules', json_encode($jc_rules));
                $this->_view->assign('gd_rules', json_encode($jc_rules));
                $this->_view->assign('pj_level1_rules', json_encode($jc_rules));
                $this->_view->assign('pj_level2_rules', json_encode($jc_rules));
                $tk_rules = [];
                foreach ($tuikeLevelList as $oneLevel) {
                    array_push($tk_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('tk_zhitui_rules', json_encode($tk_rules));
                $this->_view->assign('tk_jiantui_rules', json_encode($tk_rules));
                $qd_rules = [];
                foreach ($qudaiLevelList as $oneLevel) {
                    array_push($qd_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('qd_rules', json_encode($qd_rules));
                $tg_rules = [];
                foreach ($tuiguangLevelList as $oneLevel) {
                    array_push($tg_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('tg_level1_rules', json_encode($tg_rules));
                $this->_view->assign('tg_level2_rules', json_encode($tg_rules));
                $gq_rules = [
                    'money' => '',
                    'ratio' => '',
                ];
                $this->_view->assign('gq_zigou_rules', json_encode($gq_rules));
                $this->_view->assign('gq_tuijian_rules', json_encode($gq_rules));
                $qy_rules = [
                    'ratio' => '',
                ];
                $this->_view->assign('qy_rules', json_encode($qy_rules));
                $dianpu_rules = [
                    'ratio' => '',
                ];
                $this->_view->assign('dianpu_rules', json_encode($dianpu_rules));
            }
            $this->_view->assign('levelList', $levelList->toJson());
            $this->_view->assign('gudongLevelList', $gudongLevelList->toJson());
            $this->_view->assign('tuikeLevelList', $tuikeLevelList->toJson());
            $this->_view->assign('qudaiLevelList', $qudaiLevelList->toJson());
            $this->_view->assign('tuiguangLevelList', $tuiguangLevelList->toJson());
            $this->_view->assign('guquanDefaultList', json_encode($guquanDefaultList));
            $this->_view->assign('quanyiDefaultList', json_encode($quanyiDefaultList));
            $this->_view->assign('dianpuDefaultList', json_encode($dianpuDefaultList));
            $this->_view->display('agent/bonus.html');
        }
    }

    #[参与分红]
    public function bepartakeAction()
    {
        $rows = $this->postData;
        if ($rows['id'] && $rows['id']>0){
            $this->doBepartake($rows['id']);
        }elseif($rows['ids'] && !empty($rows['ids'])){
            foreach ($rows['ids'] as $id){
                $this->doBepartake($id);
            }
        }
        ret(0, '商品参与分红设置成功');
    }

    private function doBepartake($id)
    {
        $event = 'add';
        $add_log = 1;
        $current_agentgoods = agentgoodsModel::query()->where('goods_id', $id)->first();
        if ($current_agentgoods) {
            if($current_agentgoods->status == 1){
                $add_log = 0;
            }
            agentgoodsModel::where('goods_id', $id)->update(['status' => 1]);
        } else {
            $agentGoods = [
                'goods_id'         => $id,
                'status'           => 1,
                'jc_status'        => 1,
                'jc_self_rules'    => 0,
                'jc_rules'         => '',
                'tk_status'        => 1,
                'tk_self_rules'    => 0,
                'tk_zhitui_rules'  => '',
                'tk_jiantui_rules' => '',
                'gd_status'        => 1,
                'gd_self_rules'    => 0,
                'gd_rules'         => '',
                'qd_status'        => 1,
                'qd_self_rules'    => 0,
                'qd_rules'         => '',
                'pj_status'        => 1,
                'pj_self_rules'    => 0,
                'pj_level1_rules'  => '',
                'pj_level2_rules'  => '',
                'tg_status'        => 1,
                'tg_self_rules'    => 0,
                'tg_level1_rules'  => '',
                'tg_level2_rules'  => '',
                'gq_status'        => 1,
                'gq_self_rules'    => 0,
                'gq_zigou_rules'   => '',
                'gq_tuijian_rules' => '',
            ];
            agentgoodsModel::insert($agentGoods);
        }
        if($add_log){
            \app\modules\Admin\service\Agentgoodslog::addLog([
                'goods_id' => $id,
                'event' => $event,
                'oper_type' => 'admin',
                'oper_id' => $this->auth->user_id
            ]);
        }
    }

    #[不参与分红]
    public function nopartakeAction()
    {
        $rows = $this->postData;
        if ($rows['id'] && $rows['id']>0){
            $this->donopartake($rows['id']);
        }elseif($rows['ids'] && !empty($rows['ids'])){
            foreach ($rows['ids'] as $id){
                $this->donopartake($id);
            }
        }
        ret(0, '商品不参与分红设置成功');
    }

    private function donopartake($id)
    {
        $event = 'del';
        $add_log = 0;
        $current_agentgoods = agentgoodsModel::query()->where('goods_id', $id)->first();
        if ($current_agentgoods) {
            $add_log = 1;
            if($current_agentgoods->status == 0){
                $add_log = 0;
            }
        }
        agentgoodsModel::where('goods_id', $id)->update(['status' => 0]);
        if($add_log){
            \app\modules\Admin\service\Agentgoodslog::addLog([
                'goods_id' => $id,
                'event' => $event,
                'oper_type' => 'admin',
                'oper_id' => $this->auth->user_id
            ]);
        }
    }


    #[代理佣金记录]
    public function rewardAction()
    {
        if ($this->isPost()) {
            $params   = $this->postData;
            $page     = $params['page'] ?? 1;
            $per_page = $params['rows'] ?? 10;

            $rewardModel = (new agentrewardModel())->newQuery();
            $query       = $rewardModel->with(['agent', 'buyer', 'order', 'orderItem'])->orderByDesc('created_at');
            if (isset($params['mode']) && $params['mode'] != 'all') {
                switch ($params['mode']) {
                    case 'waiting':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_WAITING);
                        break;
                    case 'accounted':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                        break;
                    case 'cancel':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                        break;
                    case 'back':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_BACK);
                        break;
                }
            }
            if (isset($params['start_on']) && !empty($params['start_on'])) {
                $query = $query->whereDate('created_at', '>=', $params['start_on']);
            }
            if (isset($params['end_on']) && !empty($params['end_on'])) {
                $query = $query->whereDate('created_at', '<=', $params['end_on']);
            }
            if (isset($params['keywords']) && !empty($params['keywords'])) {
                if (isset($params['keywordsType']) && !empty($params['keywordsType'])) {
                    switch ($params['keywordsType']) {
                        case 'agent_id':
                            $query = $query->where('agent_id', $params['keywords']);
                            break;
                        case 'agent_phone':
                            $agent_id = memberModel::query()->where('phone', $params['keywords'])->value('id');
                            $query    = $query->where('agent_id', $agent_id);
                            break;
                        case 'order_id':
                            $query = $query->where('order_id', $params['keywords']);
                            break;
                        case 'order_sn':
                            $order_id = orderModel::query()->where('order_sn', $params['keywords'])->value('id');
                            $query    = $query->where('order_id', $order_id);
                            break;
                        case 'buyer_id':
                            $query = $query->where('buyer_id', $params['keywords']);
                            break;
                        case 'buyer_phone':
                            $buyer_id = memberModel::query()->where('phone', $params['keywords'])->value('id');
                            $query    = $query->where('buyer_id', $buyer_id);
                            break;
                        case 'goods_id':
                            $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $params['keywords'])->pluck('id')->toArray());
                            break;
                        case 'goods_title':
                            $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                            break;
                    }
                }
            }
            if (isset($params['class']) && !empty($params['class'])) {
                $query = $query->where('class', $params['class']);
            }
            $total = $query->count();
            if (isset($params['sort'])) {
                $query = $query->orderBy($params['sort'] ?: 'id', (isset($params['order']) && in_array($params['order'], ['asc', 'desc'])) ? $params['order'] : 'desc');
            }
            $data = $query->offset(($page - 1) * $per_page)
                ->limit($per_page)
                ->get()->toArray();
            json([
                'total' => $total,
                'rows'  => $data
            ]);
        } else {
            $this->_view->display(strtolower($this->controller) . '/reward.html');
        }
    }

    #[代理等级变动记录]
    public function logAction()
    {
        if ($this->isPost()) {
            $params   = $this->postData;
            $page     = $params['page'] ?? 1;
            $per_page = $params['rows'] ?? 10;

            $rewardModel = (new agentlogModel())->newQuery();
            $query       = $rewardModel->with(['agent', 'before_level', 'after_level'])->orderByDesc('created_at');
            if (isset($params['start_on']) && !empty($params['start_on'])) {
                $query = $query->whereDate('created_at', '>=', $params['start_on']);
            }
            if (isset($params['end_on']) && !empty($params['end_on'])) {
                $query = $query->whereDate('created_at', '<=', $params['end_on']);
            }
            if (isset($params['keywords']) && !empty($params['keywords'])) {
                if (isset($params['keywordsType']) && !empty($params['keywordsType'])) {
                    switch ($params['keywordsType']) {
                        case 'id':
                            $query = $query->where('agent_id', $params['keywords']);
                            break;
                        case 'phone':
                            $agent_id = memberModel::query()->where('phone', $params['keywords'])->value('id');
                            $query    = $query->where('agent_id', $agent_id);
                            break;
                        case 'nickname':
                            $agent_ids = memberModel::query()->where('nickname', 'like', "%{$params['keywords']}%")->pluck('id');
                            $query     = $query->whereIn('agent_id', $agent_ids);
                            break;
                    }
                }
            }
            $total = $query->count();
            if (isset($params['sort'])) {
                $query = $query->orderBy($params['sort'] ?: 'id', (isset($params['order']) && in_array($params['order'], ['asc', 'desc'])) ? $params['order'] : 'desc');
            }
            $data = $query->offset(($page - 1) * $per_page)
                ->limit($per_page)
                ->get()->toArray();
            json([
                'total' => $total,
                'rows'  => $data
            ]);
        } else {
            $this->_view->display(strtolower($this->controller) . '/log.html');
        }
    }

    #[代理商导出]
    public function exportAction()
    {
        $type     = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $level = $this->get('level');

        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        $filename = 'agent' . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/agent \"type={$type}&keywords={$keywords}&level={$level}&startOn={$startOn}&endOn={$endOn}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
			if( $webpath = syncFile($filepath) ){
                ret(0, '代理导出excel成功', $webpath);
            }
        }
        ret(30003, '代理导出失败');
    }

    #[代理商分红导出]
    public function exportRewardAction()
    {
        $type     = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $mode = $this->get('mode');
        $class = $this->get('class');

        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        $filename = 'agentreward' . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/agentreward \"type={$type}&keywords={$keywords}&mode={$mode}&class={$class}&startOn={$startOn}&endOn={$endOn}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
			if( $webpath = syncFile($filepath) ){
                ret(0, '代理分红导出excel成功', $webpath);
            }
        }
        ret(30003, '代理分红导出失败');
    }

    #[代理团队]
    public function teamAction()
    {
        $id = $this->get('id');
        if ($this->isPost()) {
            $rows  = DB::table('member_children')
                ->where('member_id', $id)
                ->groupBy('level')
                ->select('member_id', 'level', DB::raw('count(*) as counter'))
                ->get();
            $total = $rows->count();
            json(['total' => $total, 'rows' => $rows]);
        } else {
            $name = $this->get('name');
            $this->_view->assign('id', $id);
            $this->_view->assign('name', $name);
            $levelList       = agentlevelModel::get();
            $this->_view->assign('levelList', $levelList);
            $this->_view->display(strtolower($this->controller) . '/team.html');
        }
    }

    #[代理商团队业绩列表]
    public function teamconsumelistAction()
    {
        if ($this->isPost()) {
            $startOn = $this->get('start_on');
            if (!empty($startOn)) {
                array_push($this->condition, ['created_at', '>=', $startOn]);
            }
            $endOn = $this->get('end_on');
            if (!empty($endOn)) {
                array_push($this->condition, ['created_at', '<=', $endOn]);
            }
            $level = $this->get('level');
            if ($level) {
                array_push($this->condition, ['level', '=', $level]);
            }
            $keywordsType = $this->get('keywordsType');
            $keywords     = $this->get('keywords');
            if ($keywords) {
                array_push($this->search, [$keywordsType, '=', $keywords]);
            }
            $returnData = parent::indexAction(true);

            json($returnData);
        } else {
            $this->_view->assign('agentLevel', agentlevelModel::select('level', 'name')->get()->toJson());
            $this->_view->display( strtolower($this->controller) . '/teamconsumelist.html');
        }
    }

    #[代理商团队业绩调整]
    public function teamconsumeadjustAction()
    {
        if ($this->isPost()) {
            $rows  = $this->postData;
            $roles = [
                'member_id' => ['role' => "required|exists:member.id", 'msg' => '会员'],
                'teamconsume'     => ['role' => "required|neq:0", 'msg' => '团队业绩调整数值'],
            ];
            Validate::check($rows, $roles);
            $remark = !empty($rows['remark'])?$rows['remark']:'无';
            try {
                DB::beginTransaction();
                memberModel::teamConsume($rows['teamconsume'], $rows['member_id'], 'adjustment', '0', $remark, 'admin', $this->auth->user_id);
                DB::commit();
                $result = [
                    'ret'  => 0,
                    'msg'  => '操作成功',
                ];
            } catch (Exception $e) {
                DB::rollback();
                $result = [
                    'ret' => 30001,
                    'msg' => $e->getMessage(),
                ];
            }
            json($result);
        } else {
            $id   = $this->get('id');
            $this->_view->assign('id', $id);
            $this->_view->assign('curr_teamconsume', memberModel::where('id', $id)->value('team_consume'));
            $this->_view->display(strtolower($this->controller) . '/teamconsumeadjust.html');
        }
    }

    #[代理商团队业绩调整日志]
    public function teamconsumeadjustlogAction()
    {
        if ($this->isPost()) {
            $postData  = $this->postData;
            $page     = $params['page'] ?? 1;
            $per_page = $params['rows'] ?? 10;
            $res = [
                'total' => 0,
                'rows' => []
            ];
            if(isset($postData['id']) && is_numeric($postData['id']) && $postData['id'] > 0){
                $query = \app\modules\Admin\models\memberteamconsumeadjustlogModel::query()->with(['member'])->where('member_id', $postData['id']);
                $res['total'] = $query->count();
                $query = $query->orderByDesc('created_at');
                $data = $query->offset(($page - 1) * $per_page)
                    ->limit($per_page)
                    ->get();
                if($data){
                    $res['rows'] = $data->append(['oper_type_text', 'event_name'])->toArray();
                }
            }
            json($res);
        } else {
            $id   = $this->get('id');
            $this->_view->assign('id', $id);
            $this->_view->display(strtolower($this->controller) . '/teamconsumeadjustlog.html');
        }
    }
}
